﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZBJF.Warranty.ALiAPI;
using ZBJF.Warranty.ALiAPI.Model;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.Data;
using ZBJF.Warranty.Common.Enums.InsuranceOrder;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceProducts;
using ZBJF.Warranty.Model.ViewModel.Product;
using ZBJF.Warranty.TheThirdPartyInteraction.Sellers.ChiDu.Model.Request;

namespace ZBJF.Warranty.TheThirdPartyInteraction.Sellers.ChiDu
{
    public class ChiDuHelper
    {

        #region 发送审核通知消息给客服 + async Task SendMessage(string saleName, string userName, string checkTimeRemaining, int insuranceOrderID)
        /// <summary>
        /// 发送审核通知消息给客服
        /// </summary>
        /// <param name="saleName">销售商名称</param>
        /// <param name="userName">客户名字</param>
        /// <param name="checkTimeRemaining">剩余审核时间</param>
        /// <param name="insuranceOrderID">保单ID</param>
        /// <returns></returns>
        public static async Task SendMessage(string saleName, string userName, string checkTimeRemaining, int insuranceOrderID)
        {
            await Task.Run(() =>
            {
                int customerServiceId = 0;
                //获取任务量最少的客服电话
                string customerPhone = ServiceFactory.CustomerServiceAndInsuranceOrderMappingServiceInstance.GetLessTaskCustomerServicePhone(ref customerServiceId);

                ServiceFactory.CustomerServiceAndInsuranceOrderMappingServiceInstance.AddEntities(new CustomerServiceAndInsuranceOrderMapping()
                {
                    CustomerServiceID = customerServiceId,
                    CreateTime = DateTime.Now,
                    CheckResult = 0,
                    InsuranceOrderID = insuranceOrderID
                });
                //没有人在线， 发送给小白 18926488961 --下发运营通道不支持
                if (string.IsNullOrEmpty(customerPhone))
                    customerPhone = "18926488961";
                //发短信给客服
                ALiMessageHelper mess = new ALiMessageHelper();
                IALiTemplateParam<OrderCheckModel> template = new OrderCheckParam(new OrderCheckModel(saleName, userName, checkTimeRemaining + "分钟"));
                bool resultMess = mess.SendMessage(customerPhone, template);

                if (!resultMess)
                {
                    LogHelper.WriteLog("发送审核消息给客服失败（SendMessage）；" + saleName + "、" + userName + "、" + checkTimeRemaining, LogType.remark);
                }
            });
        }
        #endregion


        #region 保存图片 + async Task SaveImage(string url, long insuranceOrderId)
        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="url">网络路径</param>
        /// <param name="insuranceOrderId">保单ID</param>
        /// <returns>文件保存相对路径</returns>
        public static async Task SaveImage(string url,long insuranceServiceProjectId, byte serviceProductType )
        {
            DateTime nowTime = DateTime.Now;
            //保存图片.Factory.StartNew
            await Task.Run(() =>
            {
                try
                {
                    string temp = string.Format("/UploadFile/File/{0}/{1}/{2}/", nowTime.Year, nowTime.Month, nowTime.Day);
                    string path = System.Web.Hosting.HostingEnvironment.MapPath(temp);
                    string name = nowTime.ToString("HHmmssffff") + ".jpg";
                    string fileName = FileHelper.SaveNetworkImage(url, path, name, true);
                    //保存失败就直接返回网络路径
                    if (!File.Exists(path + name))
                    {
                        fileName = url;
                        LogHelper.WriteLog("处理尺度提交保单信息__保存图片失败：图片URL：" + url, LogType.remark);
                    }
                    else
                    {
                        fileName = temp + name;
                    }
                    var imageServer = ServiceFactory.InsuranceOrderImageServiceInstance;
                    InsuranceOrderImage imageInfo = imageServer.LoadByInsuranceServiceProjectId(insuranceServiceProjectId, serviceProductType).FirstOrDefault();
                    if (imageInfo != null)
                    {
                        imageInfo.NetworkUrl = url;
                        imageInfo.ImageUrl = fileName;
                        imageInfo.CreateTime = nowTime;
                        ServiceFactory.InsuranceOrderImageServiceInstance.UpdateEntities(imageInfo);
                    }
                    else
                    {
                        imageInfo = new InsuranceOrderImage();
                        imageInfo.CreateBy = "福建尺度";
                        imageInfo.CreateTime = nowTime;
                        imageInfo.ImageType = (byte)InsuranceImageType.Insurance;
                        imageInfo.ImageUrl = fileName;
                        imageInfo.InsuranceOrderServiceProjectId = insuranceServiceProjectId;
                        imageInfo.ServiceProjectType = serviceProductType;
                        imageInfo.NetworkUrl = url;
                        imageInfo = ServiceFactory.InsuranceOrderImageServiceInstance.AddEntities(imageInfo);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("保持尺度图片过程异常：" + ex.ToString() + ";Url:" + url + ";insuranceServiceProjectId:" + insuranceServiceProjectId, LogType.error);
                }
            });
        }
        #endregion

        #region 验证信息是否被篡改 + bool ValidateMessage(InsuranceOrderInfoParam param,string secretKey)
        /// <summary>
        /// 验证信息是否被篡改
        /// </summary>
        /// <param name="param">参数</param>
        /// <param name="secretKey">密钥</param>
        /// <returns></returns>
        public static bool ValidateMessage(InsuranceOrderInfoParam param, string secretKey)
        {
            EncryptionParamData vali = new EncryptionParamData(secretKey);
            vali.SetValue("SellerBusinessNo", param.SellerBusinessNo);
            vali.SetValue("SellerInsuranceProductsCode", param.SellerInsuranceProductsCode);
            vali.SetValue("SaleEmployeeId", param.SaleEmployeeId);
            vali.SetValue("UserName", param.UserName);
            vali.SetValue("UserPhone", param.UserPhone);
            vali.SetValue("CertificateType", param.CertificateType);
            vali.SetValue("CertificateNO", param.CertificateNO);
            vali.SetValue("IMEI", param.IMEI);
            vali.SetValue("ModelId", param.ModelId);
            vali.SetValue("CertificateImageUrl", param.CertificateImageUrl);
            vali.SetValue("Timestamp", param.Timestamp);
            vali.SetValue("Sign", param.Sign);
            bool result = vali.CheckSign();
            if (!result)
            {
                LogHelper.WriteLog("处理尺度提交保单信息__请求内容加密sign错误：尺度sign：" + param.Sign + "；本地sign：" + vali.MakeSign(), LogType.remark);
            }
            return result;
        }
        #endregion

        #region 验证用户购买保险成功-提交保单信息 + bool ValidateBuyResultNoticeParam(BuyResultNoticeParam param, string secretKey)
        /// <summary>
        ///  验证用户购买保险成功-提交保单信息
        /// </summary>
        /// <param name="param"></param>
        /// <param name="secretKey"></param>
        /// <returns></returns>
        public static bool ValidateBuyResultNoticeParam(BuyResultNoticeParam param, string secretKey)
        {
            EncryptionParamData vali = new EncryptionParamData(secretKey);
            vali.SetValue("SellerBusinessNo", param.SellerBusinessNo);
            vali.SetValue("ThirdOrderNO", param.ThirdOrderNO);
            vali.SetValue("Timestamp", param.Timestamp);
            vali.SetValue("Sign", param.Sign);
            bool result = vali.CheckSign();
            if (!result)
            {
                LogHelper.WriteLog("处理尺度提交保单信息__请求内容加密sign错误：尺度sign：" + param.Sign + "；本地sign：" + vali.MakeSign(), LogType.remark);
            }
            return result;
        }
        #endregion
        
    }
}
